'''
实现将图片批量导出到word
'''
import os
from PIL import Image, ImageOps
from docx import Document
from docx.shared import Inches, Pt

def __create_temp_dir__(dir):
    if os.path.exists(dir) is False:
        os.mkdir(dir)
def images_to_word(image_folder, output_word):
    # 获取文件夹中的所有图片文件
    image_files = [f for f in os.listdir(image_folder)]

    # 创建一个新的Word文档
    doc = Document()

    for filename in image_files:
        if filename.endswith(('.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG', '.bmp', '.BMP', '.tif', '.TIF', '.tiff', '.TIFF')):
            print('图片'+filename+'正在导入word中')
            image_path = os.path.join(image_folder, filename)
            # 打开图片并修正方向
            __create_temp_dir__(temp_folder)
            with Image.open(image_path) as image:
                # 检测并修正图片方向
                image = ImageOps.exif_transpose(image)
                # 保存修正后的图片到一个临时文件
                image_path = os.path.join(temp_folder, filename)
                image.save(image_path)
            img = Image.open(image_path)

            # 计算图片缩放比例，保持图片比例
            img_width, img_height = img.size
            aspect_ratio = img_width / img_height
            max_width = 6.5  # Word页面宽度（英寸），减去边距
            max_height = 8.5  # Word页面高度（英寸），减去边距以及文字高度

            if aspect_ratio > max_width / max_height:
                img_width = max_width
                img_height = max_width / aspect_ratio
            else:
                img_height = max_height
                img_width = max_height * aspect_ratio

            # 添加段落用于文字说明
            paragraph = doc.add_paragraph()
            run = paragraph.add_run(filename.split('.')[0])
            run.bold = True
            run.font.size = Pt(12)
            paragraph.alignment = 1  # 居中对齐

            # 添加图片
            doc.add_picture(image_path, width=Inches(img_width), height=Inches(img_height))

            # 添加分页符
            doc.add_page_break()

    # 保存Word文档
    doc.save(output_word)

# 使用示例
image_folder = 'D:\Signorino'
temp_folder = image_folder + '_temp'
output_word = 'D:\output.docx'
images_to_word(image_folder, output_word)
